/*
 * Amkai Enterprise Solution (AES.) 
 * Copyright 2004 by Amkai(TM), Inc.
 * www.amkai.com
 * 
 * Project: webservice
 * Package: com.amkai.aes.webservice.binary.objecthandler.relationship
 * File: RelationshipManager.java
 * Created: Feb 24, 2006 10:27:18 AM
 * Author: johnny 
 * 
 */
package com.amkai.aes.webservice.binary.objecthandler.registration;

import java.io.Serializable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.amkai.aes.aescommon.service.binary.job.relationship.PersonRelationshipJob;
import com.amkai.aes.aescommon.service.result.relationship.PersonRelationShipResultKind;
import com.amkai.aes.aescommon.service.result.relationship.PersonRelationshipResult;
import com.amkai.aes.generatedbeans.registration.Person;
import com.amkai.aes.generatedbeans.registration.items.Relationship;
import com.amkai.aes.server.extensions.relationship.RelationshipEntryManager;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;
import com.sun.corba.se.pept.encoding.InputObject;

/**
 * RelationshipManager
 * @author johnny
 * Description:
 *
 */
public class RelationshipHandler implements JobObjectHandler<PersonRelationshipJob, Serializable, PersonRelationshipResult> {
	private static final Log logger = LogFactory.getLog(RelationshipHandler.class);
	
	/** 
	 * Overriden method
	 * @param job
	 * @param object
	 * @return
	 * @throws Exception
	 * @see com.amkai.aes.webservice.binary.JobObjectHandler#process(E, InputObject)
	 * 
	 */
	public PersonRelationshipResult process(PersonRelationshipJob job, Serializable object) throws Exception {
		PersonRelationshipResult result = new PersonRelationshipResult();

		SessionManager sm = SiteManager.Start();
		try {
			sm.openSession();
			sm.openTransaction();
			
			Person personA = sm.get(Person.class, job.getPersonA());
			Person personB = sm.get(Person.class, job.getPersonB());
			
			if (job.isSet()) {
				Relationship relationship = null;
				if (job.getRelationship() != null) {
					relationship = sm.get(Relationship.class, job.getRelationship());
					RelationshipEntryManager.setRelationship(sm, personA, personB, relationship, job.getRelationshipEntryKind());
				}
			}
			else {
				Relationship r = RelationshipEntryManager.getRelationship(sm, personA, personB);
				result.setRelationship(r);
			}
			result.setKind(PersonRelationShipResultKind.SUCCESS);
			sm.commitTransaction();
		}
		catch (Exception ex) {
			logger.error("RelationshipHandler: ", ex);
			sm.rollbackTransaction();
			throw ex;
		}
		finally {
			sm.closeSession();
		}
		return result;
	}
	
}
